﻿using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using ImageAppDataModels;
using BrainTechLLC;
using BrainTechLLC.WPF;
using BrainTechLLC.ThreadSafeObjects;
using ImageAppViewModels;
using System;
using DragDropLibrary;
using System.Windows.Controls.Primitives;

namespace WpfImageDuplicates
{
    /// <summary>
    /// Interaction logic for GroupsViewControl.xaml
    /// </summary>
    public partial class GroupsViewControl : UserControl
    {
        public static readonly DependencyProperty GroupCollectionViewModelProperty =
            DependencyProperty.Register("GroupCollectionViewModel", typeof(GroupCollectionViewModel), typeof(GroupsViewControl), new PropertyMetadata(null, OnGroupCollectionViewModelPropertyChanged));

        public GroupCollectionViewModel GroupCollectionViewModel
        {
            get { return (GroupCollectionViewModel)GetValue(GroupCollectionViewModelProperty); }
            set { SetValue(GroupCollectionViewModelProperty, value); }
        }

        private static void OnGroupCollectionViewModelPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            GroupsViewControl source = d as GroupsViewControl;
            GroupCollectionViewModel vNew = e.NewValue as GroupCollectionViewModel;
            GroupCollectionViewModel vOld = e.OldValue as GroupCollectionViewModel;
            source.UpdateGroupCollectionViewModel(vNew, vOld);
        }

        private void UpdateGroupCollectionViewModel(GroupCollectionViewModel viewModel, GroupCollectionViewModel viewModelOld)
        {
            GroupCollectionViewModel = viewModel;

            // Let the UI bind to the view-model.
            this.DataContext = GroupCollectionViewModel;
        }

        public GroupsViewControl()
        {
            InitializeComponent();
        }

        private void subGrid_Loaded(object sender, RoutedEventArgs e)
        {
            BrainTechLLC.WPF.TempExten.StretchListBox(sender as Grid);
        }

        private void txtNewGroupName_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Enter)
            {
                CreateNewGroup();
            }
            else if (e.Key == System.Windows.Input.Key.Escape)
            {
                btnAddGroup.IsChecked = false;
            }
        }

        private void btnCreateNewGroup_Click(object sender, RoutedEventArgs e)
        {
            CreateNewGroup();
        }

        private void CreateNewGroup()
        {
            string groupName = txtNewGroupName.Text;
            if (string.IsNullOrEmpty(groupName))
            {
                btnAddGroup.IsChecked = false;
                return;
            }
            var found = GroupCollectionViewModel.FindGroup(groupName);

            if (found != null)
            {
                MessageBox.Show("That group name already exists");
                return;
            }

            GroupCollectionViewModel.AddOrFindGroup(groupName);
            btnAddGroup.IsChecked = false;
        }

        public void DropOntoImageCollectionView(DropEventArgs<object> e)
        {
            if (e.DroppedOnto == this || e.DroppedOnto == lstGroups)
            {
                if (DragAndDrop.GetRegisterDropTargetName(e.DroppedOnto) == "GroupView")
                {
                    if (DragAndDrop.GetRegisterDragSourceName(e.DragSource) == "ImageCollectionView")
                    {
                        ListBox listBox = e.DragSource as ListBox;
                        FileImageViewModel vmSingleSource = e.Object as FileImageViewModel;
                        if (vmSingleSource == null)
                        {
                            return;
                        }

                        foreach (FileImageViewModel vmSource in listBox.SelectedItems)
                        {
                            var item = this.lstGroups.InputHitTest(e.DropPoint);

                            System.Windows.Controls.TextBlock tb = item as System.Windows.Controls.TextBlock;

                            if (tb == null)
                            {
                                var fe = BrainTechLLC.WPF.TempExten.GetAllChildren<TextBlock>(item as FrameworkElement, true);
                                if (fe != null && fe.Count > 0)
                                {
                                    tb = fe[0];
                                }
                            }

                            if (tb != null)
                            {
                                GroupViewModel vmDest = tb.Tag as GroupViewModel;

                                if (vmDest != null)
                                {
                                    GroupCollectionViewModel.AddFileImageToGroup(vmSource.FileName, vmDest.GroupName);
                                }
                            }
                        }
                        //FileImageViewModel vmSource = e.Object as FileImageViewModel;
                        //if (vmSource != null)
                        //{
                        //    var item = this.lstGroups.InputHitTest(e.DropPoint);

                        //    System.Windows.Controls.TextBlock tb = item as System.Windows.Controls.TextBlock;

                        //    if (tb == null)
                        //    {
                        //        var fe = BrainTechLLC.WPF.TempExten.GetAllChildren<TextBlock>(item as FrameworkElement, true);
                        //        if (fe != null && fe.Count > 0)
                        //        {
                        //            tb = fe[0];
                        //        }
                        //    }

                        //    if (tb != null)
                        //    {
                        //        GroupViewModel vmDest = tb.Tag as GroupViewModel;

                        //        if (vmDest != null)
                        //        {
                        //            GroupCollectionViewModel.AddFileImageToGroup(vmSource.FileName, vmDest.GroupName);
                        //        }
                        //    }
                        //}
                    }
                }
            }
        }

        private void txtGroupName_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            System.Windows.Controls.TextBlock tb = sender as System.Windows.Controls.TextBlock;
            GroupViewModel vm = tb.Tag as GroupViewModel;
            HideOrShowFilesInGroup(tb);
        }

        private static void HideOrShowFilesInGroup(FrameworkElement tb)
        {
            ListBoxItem parentItem = BrainTechLLC.WPF.TempExten.FindParent<ListBoxItem>(tb);
            var found = parentItem.GetAllChildren<Grid>(true).FirstOrDefault(o => o.Name == "listOfFiles") as Grid;
            found.Visibility = found.Visibility == System.Windows.Visibility.Collapsed ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
        }

        private void removeFileImage_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            Image img = sender as Image;
            FileImageGroupViewModel vm = img.Tag as FileImageGroupViewModel;
            ListBox listbox = BrainTechLLC.WPF.TempExten.FindParent<ListBox>(img);
            var allSelected = listbox.GetSelected<FileImageGroupViewModel>();
            if (allSelected.FirstOrDefault(o => o.FileName == vm.FileName) == null)
            {
                allSelected.Add(vm);
            }

            allSelected.ForEach(o => GroupCollectionViewModel.RemoveFileImageFromGroup(o));
            if (GroupCollectionViewModel.AllFileImageGroupViewModels.Count == 0)
            {
                listbox.Visibility = listbox.Visibility == System.Windows.Visibility.Collapsed ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            }

        }

        private void lstGroups_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (GroupCollectionViewModel.CurrentlySelectedGroupsInListbox.Count > 0)
            {
                GroupCollectionViewModel.CurrentlySelectedGroupsInListbox.Clear();
                GroupCollectionViewModel.OnCurrentlySelectedGroupsInListboxChanged();
            }

            if (lstGroups.SelectedItems == null || lstGroups.SelectedItems.Count == 0)
            {
            }
            else
            {
                foreach (GroupViewModel item in lstGroups.SelectedItems)
                {
                    GroupCollectionViewModel.CurrentlySelectedGroupsInListbox.Add(item);
                }
                GroupCollectionViewModel.OnCurrentlySelectedGroupsInListboxChanged();
            }
        }

        private void btnShowOnlySelectedGroups_Checked(object sender, RoutedEventArgs e)
        {
            GroupCollectionViewModel.ShowOnlySelectedGroups = true;
            Settings.Values.RaisePropertyChanged("FileNameFilter");
        }

        private void btnShowOnlySelectedGroups_Unchecked(object sender, RoutedEventArgs e)
        {
            GroupCollectionViewModel.ShowOnlySelectedGroups = false;
            lstGroups.SelectedItems.Clear();
            Settings.Values.RaisePropertyChanged("FileNameFilter");
        }

        private void mnuDeleteGroup_Click(object sender, RoutedEventArgs e)
        {
            MenuItem item = sender as MenuItem;
            GroupViewModel vm = item.Tag as GroupViewModel;
            var result = MessageBox.Show(string.Format("Are you sure you want to permanently remove the group '{0}'?", vm.GroupName), "Delete?", MessageBoxButton.YesNo);
            if (result == MessageBoxResult.Yes)
            {
                GroupCollectionViewModel.RemoveGroup(vm);
            }
        }

        private void chkSelect_Checked(object sender, RoutedEventArgs e)
        {
            CheckBox cb = sender as CheckBox;
            GroupViewModel vm = cb.Tag as GroupViewModel;

            if (vm != null)
            {
                foreach (GroupViewModel gvm in lstGroups.SelectedItems)
                {
                    gvm.IsSelected = true;
                }
                vm.IsSelected = true;

                if (GroupCollectionViewModel.ShowOnlySelectedGroups)
                {
                    Settings.Values.RaisePropertyChanged("FileNameFilter");
                }
            }
        }

        private void chkSelect_Unchecked(object sender, RoutedEventArgs e)
        {
            CheckBox cb = sender as CheckBox;
            GroupViewModel vm = cb.Tag as GroupViewModel;

            if (vm != null)
            {
                foreach (GroupViewModel gvm in lstGroups.SelectedItems)
                {
                    gvm.IsSelected = false;
                }
                vm.IsSelected = false;

                if (GroupCollectionViewModel.ShowOnlySelectedGroups)
                {
                    Settings.Values.RaisePropertyChanged("FileNameFilter");
                }
            }
        }

        private void btnAddGroup_Checked(object sender, RoutedEventArgs e)
        {
            Dispatcher.BeginInvoke(new VoidDelegate(() =>
            {
                txtNewGroupName.SelectAll();
                txtNewGroupName.Focus();
            }), System.Windows.Threading.DispatcherPriority.Background);
        }

        private void btnCloseView_Click(object sender, RoutedEventArgs e)
        {
            Settings.Values.GroupOrganizerVisible = false;
        }
    }
}
